package com.hmall.search.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.common.feign.ItemClient;
import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.ItemDoc;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class  ItemListener {
 
    @Autowired
    private ItemClient itemClient;
 
    @Autowired
    private RestHighLevelClient client;

    @RabbitListener(queues = "start.queue")
    public void listenUpQueue(Long id) {
        try {
            log.info("开始上架商品：{}", id);
            Item item = itemClient.listById(id);
            ItemDoc itemDoc = new ItemDoc(item);
            String json = JSON.toJSONString(itemDoc);
            IndexRequest request = new IndexRequest("mall").id(id.toString());
            request.source(json, XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RabbitListener(queues = "end.queue")
    public void listenDownQueue(Long id) {
        log.info("开始下架商品：{}", id);
        try {
            DeleteRequest request = new DeleteRequest("mall", id.toString());
            client.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}